import Cookie from "js-cookie";
import router from "@/router";

export default {
    namespaced: true,
    actions: {},
    mutations: {
        collapseMenu(state) {
            state.isCollapsed = !state.isCollapsed
        },
        selectMenu(state, val) {
            if (val.name !== 'home') {
                state.currentMenu = val
                let result = state.tabsList.findIndex(item => item.name === val.name)
                if (result === -1) {
                    state.tabsList.push(val)
                }
            } else {
                state.currentMenu = null
            }
        },
        delMenu(state, index) {
            state.tabsList.splice(index, 1)
        },

        // 左侧导航菜单的增删改查
        setMenu(state, val) {
            state.menu = val
            Cookie.set('menu', JSON.stringify(val)) /*存起来，防止页面刷新丢失*/
        },
        // 清空导航菜单项
        clearMenu(state) {
            state.menu = []
            Cookie.remove('menu')
        },
        // 将接收的menu添加component并注册组件路由
        addMenu(state) {
            if (!Cookie.get('menu')) {
                return
            }
            let menu = JSON.parse(Cookie.get('menu'))
            state.menu = menu
            let menuArray = []
            menu.forEach(item => {
                if (item.children) {    /*有孩子*/
                    item.children = item.children.map(i => {
                        i.component = () => import(`@/pages/${i.url}`)
                        return i
                    })
                    menuArray.push(...item.children)
                } else {                /*无孩子*/
                    item.component = () => import(`@/pages/${item.url}`)
                    menuArray.push(item)
                }
            })
            // 动态添加路由
            menuArray.forEach(item => {
                router.addRoute('main', item) /*给main路由添加子组件*/
            })
        }
    },
    state: {
        isCollapsed: true,
        tabsList: [
            {
                path: '/',
                name: 'home',
                label: '首页',
                icon: 'home'
            }
        ],
        currentMenu: null,
        // 存储路由信息
        menu: []
    },
    getters: {}
}
